import yaml from 'yaml';
import fs from 'node:fs';
import init from '../model/init.js';

let HelpPath = './plugins/help-plugin';

/*
* 本插件由Jiaozi饺子制作
* 侵权联系我删除https://gitee.com/tu-zhengxiong0925
*/

export default new class HelpInit {
    async init() {
        try {
            await this.loadConfig(); // 加载配置文件
            await this.globalHelpVersion(); // 全局声明版本
            
            return { boolean: true, msg: null };
        } catch (error) {
            return { boolean: false, msg: error.message };
        }
    }

    async loadConfig() {
        let configFolder = `${HelpPath}/config`;
        let defSetFolder = `${HelpPath}/defSet`;
        const configFiles = ['config.yaml', 'help.yaml', 'helppro.yaml', 'sshelp.yaml', 'jshelp.yaml'];

        if (!fs.existsSync(configFolder)) {
            fs.mkdirSync(configFolder, { recursive: true });
        }

        for (const file of configFiles) {
            const configFilePath = `${configFolder}/${file}`;
            const defConfigFilePath = `${defSetFolder}/${file}`;
            if (!fs.existsSync(configFilePath)) {
                fs.copyFileSync(defConfigFilePath, configFilePath);
                console.log(`配置文件 ${file} 已复制到 ${configFolder}`);
            }
        }

        // 删除 .git 目录
        const gitFolderPath = `${HelpPath}/.git`;
        if (fs.existsSync(gitFolderPath)) {
            this.deleteFolderRecursive(gitFolderPath);
            console.log('初始化完成');
        }
    }

    deleteFolderRecursive(folderPath) {
        if (fs.existsSync(folderPath)) {
            fs.readdirSync(folderPath).forEach(file => {
                const currentPath = `${folderPath}/${file}`;
                if (fs.statSync(currentPath).isDirectory()) {
                    this.deleteFolderRecursive(currentPath);
                } else {
                    fs.unlinkSync(currentPath);
                }
            });
            fs.rmdirSync(folderPath);
        }
    }

    async globalHelpVersion() {
        let HelpPluginVersion = JSON.parse(fs.readFileSync(`${HelpPath}/package.json`, 'utf-8'));
        HelpPluginVersion = HelpPluginVersion.version;
        global.HelpPluginVersion = HelpPluginVersion;
    }
}
